package com.sychip.fhc.lib.base


import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.input.OffsetMapping
import androidx.compose.ui.text.input.TransformedText
import androidx.compose.ui.text.input.VisualTransformation
import timber.log.Timber
import java.text.DecimalFormatSymbols

class DecimalInputVisualTransformation(
    private val decimalFormatter: DecimalFormatter
) : VisualTransformation {

    override fun filter(text: AnnotatedString): TransformedText {
val minusSign = DecimalFormatSymbols.getInstance().minusSign
        val isNegative = text.text.startsWith(minusSign)
        val inputText = text.text.replace(minusSign.toString(),"",true)


        var formattedNumber = decimalFormatter.formatForVisual(inputText)
        var contentLength  = inputText.length

        if(isNegative){
            formattedNumber = "-$formattedNumber"
            contentLength = contentLength + 1
        }
        val newText = AnnotatedString(
            text = formattedNumber,
            spanStyles = text.spanStyles,
            paragraphStyles = text.paragraphStyles
        )

        val offsetMapping = FixedCursorOffsetMapping2(
            contentLength = contentLength,
            formattedContentLength = formattedNumber.length
        )
       return TransformedText( newText, offsetMapping)
    }
}

private class FixedCursorOffsetMapping2(
    private val contentLength: Int,
    private val formattedContentLength: Int,
) : OffsetMapping {
    override fun originalToTransformed(offset: Int): Int = formattedContentLength
    override fun transformedToOriginal(offset: Int): Int = contentLength
}


class DecimalFormatter(
    symbols: DecimalFormatSymbols = DecimalFormatSymbols.getInstance(),
) {

    private val thousandsSeparator = symbols.groupingSeparator
    private val decimalSeparator = symbols.decimalSeparator
    private val minusSign = symbols.minusSign

    fun cleanup(input: String, cursorIdx: Int = 0, min: Double, max: Double, isInt: Boolean = false):  Pair<Int, String> {
        var _cursorIdx = cursorIdx
        Timber.i("    DecimalFormatter 1111>>>>>>>>>>>>>>>>>>>>>>>>> $input    $_cursorIdx")
        var _input = input
        if ( _input.startsWith(".")){
            _input = "0$_input"
        }
        if ( _input.indexOf("..") >=0 ){
            _input = _input.replace("..", ".")
            _cursorIdx -= 1
        }
        if ( _input.startsWith("00")){
            _input = _input.substring(1)
            _cursorIdx -= 1
        }
        if ( _input.startsWith("--")){
            _input = _input.substring(1)
            _cursorIdx -= 1
        }
        Timber.i("    DecimalFormatter 22222>>>>>>>>>>>>>>>>>>>>>>>>> $_input    $_cursorIdx")
        if (_input.matches("\\D-".toRegex())) return Pair( _cursorIdx, "")
        if (_input.matches("0+".toRegex())) return Pair( _cursorIdx, "0")

        var isNegative = _input.startsWith(minusSign)
//        if(decimalplaces > 0 && _input.indexOf(".")<0){
//            _input = "$_input.0"
//        }
//        val arrNum = _input.split(".")
//        while(arrNum[1].length < decimalplaces){
//            _input= "{$_input}0"
//        }

        if ( _input.indexOf(minusSign) >= 0){
            _input=  input.replace(minusSign.toString(),"",true)

        }
        _input = _input.replace(minusSign.toString(),"",true)


        val sb = StringBuilder()

        var hasDecimalSep = false

        for (char in _input) {
            if (char.isDigit()) {
                sb.append(char)
                continue
            }
            if (char == minusSign) {
                sb.append(char)
            }
            if (char == decimalSeparator && !hasDecimalSep && sb.isNotEmpty()) {
                sb.append(char)
                hasDecimalSep = true
            }
        }
        _input = sb.toString()
        if(isNegative) {
            _input = minusSign.toString() + _input
        }
        if(_input != "-" && _input.isNotEmpty()){
            if( _input.toDouble() > max){
                _input = max.toString()
                isNegative = _input.startsWith(minusSign)
            }
            if( _input.toDouble() < min){
                _input = min.toString()
                isNegative = _input.startsWith(minusSign)
            }
        }
        if(isInt){
            _input = _input.split(".")[0]
        }

        _cursorIdx = _input.length
        return Pair( _cursorIdx, _input)
    }

    fun formatForVisual(input: String): String {

        val split = input.split(decimalSeparator)

        val intPart = split[0]
            .reversed()
            .chunked(3)
            .joinToString(separator = thousandsSeparator.toString())
            .reversed()

        val fractionPart = split.getOrNull(1)

        return if (fractionPart == null) intPart else intPart + decimalSeparator + fractionPart
    }
}

